/*
 * @Author: 黄达全
 * @Date: 2024-07-29 10:25:09
 * @LastEditTime: 2024-08-08 16:11:40
 */
import router, { addRoute } from "@/router"
import config from "@/config"
import tool from "./utils/tool";
import { JwtTokenConstant } from "@/common/constant"
import useElementPlus from "@/hooks/useElementPlus"
import ManagerApi from "@/api/model/manager"

const { message } = useElementPlus()
let init = true
router.beforeEach(async (to, from, next) => {

    const token = tool.data.get(JwtTokenConstant.token)

    // 没有登录，强制跳转回登录页
    if (!token && to.path != "/login") {
        if (init) {
            init = false
            return next({ path: "/login" })
        }
        message({ message: `请先登录`, type: "error" })
        return next({ path: "/login" })
    }

    // 登录了，强制跳转回首页
    if (token && to.path == "/login") {
        message({ message: `请勿重复登录`, type: "error" })
        return next({ path: from.path ? from.path : "/" })
    }

    let hasNewRoutes = false;
    if (token) {
        try{
            const menus =(await ManagerApi.getUserInfo()).data.menus
            tool.data.set(JwtTokenConstant.menu, menus)
            hasNewRoutes = addRoute(menus)
        }catch(e){
            console.log(e)
                // Token 过期或无效，跳转到登录页面
                tool.data.remove(JwtTokenConstant.token);
                tool.data.clear()
                return next({ path: "/login" });
            }
        }

    document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`;
    hasNewRoutes ? next(to.fullPath) : next()
})